package com.cc.jdkjucdemo.CompletableFuture;

import java.util.concurrent.*;

public class CompletableFutureDemo02 {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            50,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程start ......");
        // 没有返回结果，可以执行任务
        CompletableFuture<Void> whenCompleteAsync1 = CompletableFuture.runAsync(() -> {
                    System.out.println("子线程执行了：" + Thread.currentThread().getName());
                    int i = 10 / 0;
                }, executor)
//                .whenCompleteAsync((res, exec) -> {
//                    System.out.println("whenCompleteAsync1");
//                    System.out.println("res = " + res);
//                    System.out.println("exec = " + exec);
//                })
                .exceptionally((exec) -> {
                    // 发生异常处理
                    System.out.println("exec1 = " + exec);
                    return null;
                });
        whenCompleteAsync1.get();

        // 带返回结果
//        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
//            System.out.println("子线程2执行了：" + Thread.currentThread().getName());
//            int i = 10 / 0;
//            return 10;
//        }, executor).whenCompleteAsync((res, exec) -> {
//            System.out.println("whenCompleteAsync2");
//            System.out.println("res = " + res);
//            System.out.println("exec = " + exec);
//        }).exceptionally((exec) -> {
//            // 发生异常处理，带返回值
//            System.out.println("exec2" + exec);
//            return -1;
//        });
//        Integer integer = integerCompletableFuture.get();
//        System.out.println(integer);

        System.out.println("主线程end ......");
        executor.shutdown();
    }
}
